<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of login
 *
 * @author Administrator
 */
class login extends CI_Controller {

  //put your code here
  public function __construct() {
    parent::__construct();
  }

  private function _validate($email, $password, $prefix = '') {
    $user_message = '';
    if (empty($email)) {
      $user_message = $this->lang->line('error.login.email.require');
    } else if (strlen($email) < 3) {
      $user_message = $this->lang->line('error.login.minimum', 3);
    }
    $password_message = '';
    if (empty($password)) {
      $password_message = $this->lang->line('error.login.password.require');
    } else if (strlen($password) < 6) {
      $password_message = $this->lang->line('error.login.minimum', 6);
    }
    if (!empty($user_message) || !empty($password_message)) {
      return '[' . (empty($user_message) ? '' : '["' . $prefix . '_' . 'email",false,"' . $user_message . '"]') .
              (!empty($user_message) && !empty($password_message) ? ',' : '') .
              (empty($password_message) ? '' : '["' . $prefix . '_' . 'password",false,"' . $password_message . '"]') . ']';
    }
    return '';
  }

  public function index($prefix = '') {
    $email = isset($_REQUEST['email']) ? $_REQUEST['email'] : '';
    $password = isset($_REQUEST['password']) ? $_REQUEST['password'] : '';
    $errors = $this->_validate($email, $password, $prefix);
    if (empty($errors)) {
      $end_user = $this->end_user_model->get(array('email' => $email, 'status' => PROFILE_STATUS_ACTIVE));
      if ($end_user) {
        $user = $this->user_model->get(array('id' => $end_user['user_id'], 'is_active' => true));
        if (!empty($user)) {
          $password = md5($user['salt'] . md5($password));
          if ($user["password"] == $password) {
            unset($user['password']);
            $user['last_login'] = time();
            $this->user_model->save($user);
            $end_user['last_login'] = time();
            $this->end_user_model->save($end_user);
            set_userdata('end_user_user_id', $user['id']);
            set_userdata('end_user_role', 'END-USER');
            set_userdata('end_user_display_name', $user['display_name']);
            set_userdata('end_user_id', $end_user['id']);
            set_userdata('end_user_avatar', $end_user['avatar']);
            set_userdata('country_id', $end_user['country_id']);
            set_userdata('state_id', $end_user['state_id']);
            set_userdata('city_id', $end_user['city_id']);
            set_userdata('subcrised', TRUE);
            echo '[]';
            return;
          }
        }
      }
      echo '[["' . $prefix . '_' . 'password",false,"' . $this->lang->line('error.login.password.incorrect') . '"]]';
    } else
      echo $errors;
  }

}